package com.work.export.controller;

import com.work.export.constant.Constant;
import com.work.export.service.DataExportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import static org.slf4j.LoggerFactory.*;


// Controller 类
@RestController
@RequestMapping("/dataExport")
public class DataExportController {

    private static final Logger logger = getLogger(DataExportController.class);

    @Autowired
    private DataExportService dataExportService;

    @Autowired
    @Qualifier("customThreadPool")
    private TaskExecutor customThreadPool;

    @GetMapping("/exportAndDownload")
    public ResponseEntity<byte[]> exportAndDownload(HttpServletResponse response) {
        int threadCount = 10;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        List<String> fileNames = new ArrayList<>();

        for (int i = 0; i < threadCount; i++) {
            final int threadNumber = i + 1;
            customThreadPool.execute(() -> {
                try {
                    dataExportService.exportData(threadNumber, countDownLatch);
                    logger.info("'{}'执行...", Thread.currentThread().getName());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                fileNames.add("export_thread_" + threadNumber + ".xlsx");
            });
        }

        try {
            countDownLatch.await();  // 等待所有线程完成任务

            // 所有线程完成任务后，进行 Excel 导出逻辑
            System.out.println("所有线程都完成了它们的任务...");

            // 压缩文件夹
            String zipFileName = "exported_data.zip";
            dataExportService.compressFilesAndDownload(fileNames, zipFileName);

            // 下载压缩包
            File zipFile = new File(Constant.EXPORT_PATH + File.separator + zipFileName);
            byte[] zipBytes = getBytes(zipFile);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", zipFileName);
            headers.setContentLength(zipBytes.length);

            return new ResponseEntity<>(zipBytes, headers, HttpStatus.OK);
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private byte[] getBytes(File file) throws IOException {
        try (InputStream is = new FileInputStream(file)) {
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            return bytes;
        }
    }
}